package instruments;

import collision.MainWindow;
import data.ConnectionPoint;
import data.NavmeshRegion;
import data.InstrumentGraphics;
import data.Params;
import data.RegionConnection;
import java.awt.Color;

/**
 * @author sad
 */
public class AbstractPolygonInstrument extends Instrument {

    private int cellsCount = 0;

    public void clearAffectance(){
        for(NavmeshRegion p:MainWindow.getInstance().getExtAreas()){
            p.clearAffectance();
        }
    }
    
    @Override
    public void onDraw(InstrumentGraphics g) {
        cellsCount = 0;
        super.onDraw(g);
        drawAllPolygons(g);
        drawAllConnectedPoints(g);
        g.setColor(Color.BLACK);
        g.drawString("Cells count = " + cellsCount, 10, 20);
    }

    protected void drawAllPolygons(InstrumentGraphics g) {
        for (NavmeshRegion tArea : MainWindow.getInstance().getExtAreas()) {
            tArea.draw(g);
            cellsCount += tArea.getCellsCount();
        }
    }

    protected void drawAllConnectedPoints(InstrumentGraphics g) {
        g.setColor(Color.YELLOW);
        for (NavmeshRegion tArea : MainWindow.getInstance().getExtAreas()) {
            double x = tArea.getX();
            double y = tArea.getY();
            if (tArea.getConnection() != null) {
                for (RegionConnection connection : tArea.getConnection().values()) {
                    drawPolygonConnection(g, connection, x, y);
                }
            }
        }
    }

    protected void drawPolygonConnection(InstrumentGraphics g, RegionConnection connection, double startX, double startY) {
        double width = Params.CELL_SIZE - 1;
        double height = Params.CELL_SIZE - 1;
        if (width <= 0) {
            width = 1;
        }
        if (height <= 0) {
            height = 1;
        }
        for (ConnectionPoint connectionPoint : connection.getConnectionPoints()) {
            double x = connectionPoint.getP1().x * Params.CELL_SIZE + startX;
            double y = connectionPoint.getP1().y * Params.CELL_SIZE + startY;
            g.fillRect(x + 1, y + 1, width, height);
        }
    }

    protected NavmeshRegion trySelect(double x, double y) {
        for (NavmeshRegion pa : MainWindow.getInstance().getExtAreas()) {
            if (pa.contains(x, y)) {
                return pa;
            }
        }

        return null;
    }
}
